import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import config from '../config';
import { AppError } from './errorHandler';

/**
 * 认证中间件 - 验证JWT令牌
 */
export const authenticate = (req: Request, res: Response, next: NextFunction) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');

    if (!token) {
      throw new AppError('未提供访问令牌', 401);
    }

    const decoded = jwt.verify(token, config.jwt.secret) as any;
    (req as any).user = decoded;
    next();
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      return next(new AppError('令牌已过期', 401));
    }
    if (error instanceof jwt.JsonWebTokenError) {
      return next(new AppError('无效的令牌', 401));
    }
    next(new AppError('认证失败', 401));
  }
};

/**
 * 授权中间件 - 检查用户角色权限
 */
export const authorize = (...roles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      const user = (req as any).user;
      
      if (!user) {
        throw new AppError('用户未认证', 401);
      }

      if (roles.length && !roles.includes(user.role)) {
        throw new AppError('权限不足', 403);
      }

      next();
    } catch (error) {
      next(error);
    }
  };
};